//
//  HttpClient.m
//  EduMobileTeacher
//
//  Created by zou tianyu on 13-8-19.
//  Copyright (c) 2013年 zou tianyu. All rights reserved.
//

#import "HttpClient.h"
#import "JSONKit.h"
#import "AFHTTPRequestOperation.h"

@implementation HttpClient

//POST请求
+(void) postHttpRequest:(NSString *)method
              withParam:(NSDictionary *)paramRequest
            withSuccess:(HttpClientSuccessBlock)success
            withFailure:(HttpClientFailureBlock)failure {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"",[[ApiClient sharedInstance] urlStringForApi:method]];

    [manager POST:url parameters:paramRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"success");
        
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        id result = [responseString objectFromJSONString];
        success(operation, result);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSString *errorResult = [error.userInfo objectForKey:@"NSLocalizedRecoverySuggestion"];
        if (errorResult
            && [errorResult objectFromJSONString]
            && [self resultHasError:[errorResult objectFromJSONString]]) {
            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:[self getGlobalError:[errorResult objectFromJSONString] withMethod:method]];
            failure(operation, commonError);
        } else {
            NSString *errordes = [error localizedDescription];
            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:errordes];
            failure(operation, commonError);
        }
        
    }];

}


/**
 *  get请求（token）
 */
+ (void)getHttpRequest:(NSString *)method
             withToken:(NSString *)token
           withSuccess:(HttpClientSuccessBlock)success
           withFailure:(HttpClientFailureBlock)failure {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    NSString *url = [NSString stringWithFormat:@"%@%@",kRequestURLString,[[ApiClient sharedInstance] urlStringForApi:method]];
//    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
//    
//    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
//        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        id result = [responseString objectFromJSONString];
//        success(operation, result);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
//        NSString *errorResult = [error.userInfo objectForKey:@"NSLocalizedRecoverySuggestion"];
//        if (errorResult
//            && [errorResult objectFromJSONString]
//            && [self resultHasError:[errorResult objectFromJSONString]]) {
//            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:[self getGlobalError:[errorResult objectFromJSONString] withMethod:method]];
//            failure(operation, commonError);
//        } else {
//            NSString *errordes = [error localizedDescription];
//            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:errordes];
//            failure(operation, commonError);
//        }
//    }];
}


//带图片的POST请求
//+(void) postHttpRequest:(NSString *)method
//              withParam:(NSDictionary *)paramRequest
//          withImageData:(NSData *)imageData
//        withUploadToken:(NSString *)token
//           withFileName:(NSString *)filename
//               withName:(NSString *)name
//            withSuccess:(HttpClientSuccessBlock)success
//            withFailure:(HttpClientFailureBlock)failure {
//    NSMutableDictionary *paramBase = [[NSMutableDictionary alloc]init];
//
//    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
////    AFHTTPRequestSerializer *requestSerial = manager.requestSerializer;
////    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
//    NSString *url = [NSString stringWithFormat:@"%@%@",kRequestURLString,[[ApiClient sharedInstance] urlStringForApi:method]];
//    NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", @"itcast"];
//    NSString *strLength = [NSString stringWithFormat:@"%ld", (long)imageData.length];
//    [manager.requestSerializer setValue:strLength forHTTPHeaderField:@"Content-Length"];
//    [manager.requestSerializer setValue:strContentType forHTTPHeaderField:@"Content-Type"];
//    [manager POST:url parameters:imageData success:^void(AFHTTPRequestOperation * operation, id responseObject) {
//        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// 
//        id result = [responseString objectFromJSONString];
//        if ([self resultHasError:result]) {
//            //返回错误代码
//            if (failure) {
//                CommonError *error = [[CommonError alloc]initWithCode:[result objectForKey:@"code"] withMessage:[self getGlobalError:result withMethod:method]];
//                failure(operation, error);
//            }
//        } else {
//            //正常结束
//            if (success) {
//                success(operation, [result objectForKey:@"result"]);
//            }
//        }
//        
//    } failure:^ void(AFHTTPRequestOperation * operation, NSError *error) {
//        id responseObject = [operation responseObject];
//        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSString *errorResult = [error.userInfo objectForKey:@"NSLocalizedRecoverySuggestion"];
//        if (errorResult
//            && [errorResult objectFromJSONString]
//            && [self resultHasError:[errorResult objectFromJSONString]]) {
//            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:[self getGlobalError:[errorResult objectFromJSONString] withMethod:method]];
//            failure(operation, commonError);
//        } else {
//            
//            NSString *errordes = [error localizedDescription];
//            CommonError *commonError = [[CommonError alloc]initWithCode:[NSString stringWithFormat:@"%ld",(long)error.code] withMessage:errordes];
//            failure(operation, commonError);
//        }
//    }];
//}


+ (BOOL)resultHasError:(id)responseObject {
  if ([responseObject isKindOfClass:[NSDictionary class]]) {
    if ([@"00000" isEqualToString:[responseObject objectForKey:@"code"]]) {
      return NO;
    } else {
      return YES;
    }
  }
  return YES;
}

+ (NSString *)getGlobalError:(id)responseObject withMethod:(NSString *)method {
//  if ([@"00001" isEqualToString:[responseObject objectForKey:@"code"]]) {
//    //illegal user
//    if ([method isEqualToString:API_AUTH_LOGIN]) {
//      return @"用户名或密码错误";
//    } else {
//      return @"身份认证失败，请重新登录";
//    }
//  } else if ([@"10004" isEqualToString:[responseObject objectForKey:@"code"]]) {
//    //illegal authorization
//    return @"身份认证失败，请重新登录";
//  } else if ([@"10005" isEqualToString:[responseObject objectForKey:@"code"]]) {
//    //expired
//    return @"身份认证过期，请重新登录";
//  } else if ([@"10008" isEqualToString:[responseObject objectForKey:@"code"]]) {
//    //expired
//    return @"用户名或密码错误";
//  } else {
//    return [responseObject objectForKey:@"message"];
//  }
    return [responseObject objectForKey:@"message"];
}

@end
